<?php

// +----------------------------------------------------------------------
// | 权限组控制器
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\pos\admin;

use app\model\pos\Pos as PosModel;
use app\model\ucenter\User as UserModel;
use app\model\pos\Store as StoreModel;
use think\Exception;
use yicmf\builder\Edit;
use yicmf\builder\Table;
use app\controller\admin\Common;
use app\event\file\Attachment as AttachmentEvent;
use app\model\pos\PosOrder as PosOrderModel;

class Pos extends Common
{
    protected function initialize()
    {
        parent::initialize();
    }

    public function _filter()
    {
        $where[] = ['status', '>', -2];
        return $where;
    }

    public function index()
    {

        $statusOptions = [
            [
                'id' => 1,
                'value' => '未划拨'
            ],
            [
                'id' => 2,
                'value' => '已划拨'
            ]
        ];
        $bindOptions = [
            [
                'id' => 1,
                'value' => '未绑定'
            ],
            [
                'id' => 2,
                'value' => '已绑定'
            ]
        ];
        $pay_c = [];

        foreach (PosModel::$channel as $index => $item) {
            $pay_c[] = [
                'id'=>$index,
                'value'=>$item,
            ];
        }
        $where = $this->_filter();
        $field = $this->request->param('field/a');
        if (!empty($field['is_bind'])) {
            if ($field['is_bind'] == 2) {
                $where[] = ['bind_time', '!=', ''];
            } else {
                $where[] = ['bind_time', '=', null];
            }
        }
        if (!empty($field['is_transfer'])) {
            if ($field['is_transfer'] == 2) {
                $where[] = ['user_id', '!=', ''];
            } else {
                $where[] = ['user_id', '=', null];
            }
        }
        if (!empty($field['sn_start'])) {
            $where[] = ['sn', '>=', $field['sn_start']];
        }
        if (!empty($field['sn_end'])) {
            $where[] = ['sn', '<=', $field['sn_end']];
        }
        if ($this->request->param('order_sn')) {
            $order_id = PosOrderModel::where('sn',$this->request->param('order_sn'))->value('id');

            $where[] = ['order_id', '=', $order_id];
        }
        // 机具序列号 支付公司 归属合伙人 机具状态 商户名称 产品类型 活动类型  等级包 入库时间  操作  产品型号 产品品牌
        $builder = new Table();
        $builder->model(PosModel::class)
            ->where($where)
            ->excel()
            ->order('id DESC')
//                ->suggest('高等级可以对低等级用户进行操作或者授权')
            ->searchSelect('is_transfer', '划拨状态', $statusOptions)
            ->searchSelect('is_bind', '绑定状态', $bindOptions)
            ->searchSelect('channel_id', '支付公司', $pay_c)
            ->searchText('agent_id', '服务商ID')
            ->searchDateTimeRange('bind_time','绑定时间')
            ->searchText('order_sn', '订单号')
            ->searchText('sn_start', '机身开始号')
            ->searchText('sn_end', '机身结束号')
//            ->searchText('result_count', '显示总数')
            ->buttonUpdate('update')
            ->buttonUpdate('pos/admin/posOrder/find', '按订单下发', '', '', ['id' => '__id'])
            ->buttonUpdate('pos/admin/User/find', '按用户下发', '', '', ['id' => '__id'])
//            ->buttonDialog('按订单下发',['url'=>'transfer?type=1','height'=>700,'width'=>600,'class'=>'layui-bg-green'])
//            ->buttonUpdate('transfer?type=1','按用户下发')
            ->keyLeftLeader('checkbox')
            ->keyId()
            ->keyText('sn', '机具序列号', false, 200)
            ->keyText('model', '产品型号')
//            ->keyText('name', '产品类型')
            ->keyMap('channel_id', '支付公司', PosModel::$channel)
            ->keyUser('user_id', '归属合伙人')
//            ->keyText('sn', '机具状态')
            ->keyText('store.nickname', '商户名称')
            ->keyText('pos_level.name', '产品等级')
            ->keyClosure('用户等级', function ($data) {
                if ($data['user_id'] && $data['is_level']) {
                    return 'V'.($data['user_id'] ? $data['user']['pos_level'] : '-');
                } else {
                    return '-';
                }
            })
//            ->keyBool('is_level', '等级包')
            ->keyText('create_time', '入库时间')
//            ->keyText('name', '产品品牌')
//				->keyUpdateTime()
            ->keyTime('bind_time', '绑定时间')
//            ->keyStatus()
//            ->quickUpdate(['title','description'])
            ->actionUpdate()
            ->actionDelete();
//            ->actionForbid('forbid?id={$id}', '禁用', function ($data) {
//                return 1 == $data['status'] && 1 < $data['id'];
//            });
        return $builder->fetch();
    }


    public function userHtml()
    {

        $statusOptions = [
            [
                'id' => 1,
                'value' => '未划拨'
            ],
            [
                'id' => 2,
                'value' => '已划拨'
            ]
        ];
        $bindOptions = [
            [
                'id' => 1,
                'value' => '未绑定'
            ],
            [
                'id' => 2,
                'value' => '已绑定'
            ]
        ];
        $where = $this->_filter();
        $field = $this->request->param('field/a');
        if (!empty($field['is_bind'])) {
            if ($field['is_bind'] == 2) {
                $where[] = ['bind_time', '!=', ''];
            } else {
                $where[] = ['bind_time', '=', null];
            }
        }
        if (!empty($field['is_transfer'])) {
            if ($field['is_transfer'] == 2) {
                $where[] = ['user_id', '!=', ''];
            } else {
                $where[] = ['user_id', '=', null];
            }
        }
        if (!empty($field['sn_start'])) {
            $where[] = ['sn', '>=', $field['sn_start']];
        }
        if (!empty($field['sn_end'])) {
            $where[] = ['sn', '<=', $field['sn_end']];
        }
        if ($this->request->param('order_sn')) {
            $order_id = PosOrderModel::where('sn',$this->request->param('order_sn'))->value('id');

            $where[] = ['order_id', '=', $order_id];
        }
        if ($this->request->param('__user_id'))
        {

            $where[]=['buy_user_id|user_id','=',$this->request->param('__user_id')];
        }

        // 机具序列号 支付公司 归属合伙人 机具状态 商户名称 产品类型 活动类型  等级包 入库时间  操作  产品型号 产品品牌
        $builder = new Table();
        $builder->model(PosModel::class)
            ->where($where)
            ->excel()
            ->setSearchPostUrl('/pos/admin/Pos/userHtml',['__user_id'=>$this->request->param('id')])
            ->order('id DESC')
//                ->suggest('高等级可以对低等级用户进行操作或者授权')
            ->searchSelect('is_transfer', '划拨状态', $statusOptions)
            ->searchSelect('is_bind', '绑定状态', $bindOptions)
//            ->searchText('result_count', '显示总数')
            ->keyId()
            ->keyText('sn', '机具序列号', false, 200)
            ->keyText('model', '产品型号')
//            ->keyText('name', '产品类型')
            ->keyMap('channel_id', '支付公司', PosModel::$channel)
            ->keyUser('user_id', '归属合伙人')
//            ->keyText('sn', '机具状态')
            ->keyText('store.nickname', '商户名称')
            ->keyText('pos_level.name', '产品等级')
            ->keyClosure('用户等级', function ($data) {
                if ($data['user_id'] && $data['is_level']) {
                    return 'V'.($data['user_id'] ? $data['user']['pos_level'] : '-');
                } else {
                    return '-';
                }
            })
            ->keyText('create_time', '入库时间')
            ->keyTime('bind_time', '绑定时间');
        return $builder->fetch();
    }


    public function update()
    {
        if ($this->request->isPost()) {
            try {
                if ($this->request->param('id')) {
                    $group = PosModel::where('id', $this->request->param('id'))->where('store_id', $this->store['id'])->find();
                    if (!$group) {
                        throw new Exception('pos不存在');
                    }
                    $group['name'] = $this->request->param('name');
                    $group['channel_id'] = $this->request->param('channel_id');
                    $group['model'] = $this->request->param('model');
                    $group['is_level'] = $this->request->param('is_level');
                    $group['sn'] = $this->request->param('sn');
                    $data['message'] = '保存成功';
                    $group->save();
                } else {
                    // 新增
                    $group['name'] = $this->request->param('name');
                    $group['is_level'] = $this->request->param('is_level');
                    $group['channel_id'] = $this->request->param('channel_id');
                    $group['model'] = $this->request->param('model');

                    $sn = explode("\n", trim($this->request->param('sn')));
                    foreach ($sn as $item) {
                        if (trim($item) != '' && !PosModel::where('sn', $item)->find()) {

                            $group['sn'] = $item;
                            $insertAll[] = $group;
                        }
                    }

                    $excel_id = $this->request->param('excel_id', '');

                    if ($excel_id) {
                        $info = AttachmentEvent::distinguish($excel_id);

                        if (is_array($info)) {
                            foreach ($info as $index => $item) {
                                if ($index > 0) {
                                    if ($group['channel_id'] == 0) {
                                        if (!PosModel::where('sn', $item[2])->where('channel_id', 0)->find()) {
                                            $group['sn'] = $item[2];
                                            $group['model'] = $item[6];
                                            unset($group['user_id']);
                                            unset($group['bind_time']);
                                            unset($group['activate_time']);
                                            if ($item[1]) {
                                                $user = UserModel::where('mobile', $item[1])->find();
                                                if ($user) {
                                                    $group['user_id'] = $user['id'];
                                                }
                                            }
                                            if ($item[4]) {
                                                $group['bind_time'] = time_format(strtotime($item[4]));
                                            }
                                            if ($item[5]) {
                                                $group['activate_time'] = time_format(strtotime($item[5]));
                                            }
                                            $group['model'] = $item[7];
                                            $group['name'] = $item[6];
                                            $insertAll[] = $group;
                                        }
                                    } else {
                                        if (!PosModel::where('sn', $item[3])->where('channel_id', 1)->find()) {
                                            $group['sn'] = $item[3];
                                            $group['model'] = $item[9];
                                            if ($item[6]) {
                                                $store = StoreModel::where('store_sn', $item[6])->where('channel_id', 1)->find();
                                                if ($store) {
                                                    $store['nickname'] = $item[7];
                                                    $store->save();
                                                } else {
                                                    $store['channel_id'] = 1;
                                                    $store['nickname'] = $item[7];
                                                    $store['store_sn'] = $item[6];
                                                    $store['pos_sn'] = $item[3];
                                                    $store = StoreModel::create($store);
                                                    if (!$store) {
                                                        throw new Exception('商户信息失败');
                                                    }
                                                }
                                                $group['store_id'] = $store['id'];
                                                $group['merch_no'] = $store['store_sn'];
                                            }
                                            unset($group['store_id']);
                                            unset($group['bind_time']);
                                            unset($group['merch_no']);
                                            if ($item[15]) {
                                                $group['bind_time'] = time_format(strtotime($item[15]));
                                            }
                                            if ($item[14]) {
                                                $group['create_time'] = time_format(strtotime($item[14]));
                                            }
                                            $group['name'] = $item[9];
                                            $insertAll[] = $group;
                                        }
                                    }

                                }
                            }
                        }
//                        dump(is_file($excel['path']));
                    }

                    $pos = new PosModel();
                    $c = $pos->saveAll($insertAll);
                    $data['message'] = '新增' . count($c) . '条成功';
                }

                $data['code'] = 0;
            } catch (Exception $e) {
                $data['code'] = 1;
                $data['message'] = $e->getMessage();
            }
            if (0 === $data['code']) {
                $this->_returnSuccess($data['message']);
            } else {
                $this->_returnError($data['message'], false);
            }
        } else {
            // 同步节点与菜单
            if ($this->request->param('id')) {
                $group_id = $this->request->param('id');
                $data = PosModel::where('id', $group_id)->find();
                if (!$data) {
                    $this->_returnError('POS机不存在');
                }
            } else {
                $data = [];
            }
            $param = [];

            $default_id = 0;
            foreach (PosModel::$brands as $brand) {
                if (0 == $default_id) {
                    $default_id = $brand['id'];
                }
                $param[$brand['id']] = $brand['name'];
            }

            $builder = new Edit();
            $builder->title('POS机管理')
                ->keyRadio('channel_id', '渠道', PosModel::$channel, '', 0)
                ->keyTextInline('name', '名称')
//                    ->keyBelongTo('document.title','im/admin/Document/index','关联常见问题')
                ->keyTextInline('model', '型号');
            if ($data) {
                $builder->keyTextInline('sn', '序列号', '');
            } else {
                $builder->keyAttachment('excel_id', '批量')
                    ->keyTextArea('sn', '序列号', '支持多个，每行一个');
            }
            $builder->keySwitch('is_level', '等级包')
                ->data($data)
                ->buttonSubmit();
            return $builder->fetch();
        }
    }


    public function transfer()
    {
        if ($this->request->isPost()) {
            try {
                if ($this->request->param('id')) {
                    $group = PosModel::where('id', $this->request->param('id'))->where('store_id', $this->store['id'])->find();
                    if (!$group) {
                        throw new Exception('pos不存在');
                    }
                    $group['name'] = $this->request->param('name');
                    $group['channel_id'] = $this->request->param('channel_id');
                    $group['model'] = $this->request->param('model');
                    $group['sn'] = $this->request->param('sn');
                    $data['message'] = '保存成功';
                    $group->save();
                } else {
                    // 新增
                    $group['name'] = $this->request->param('name');
                    $group['channel_id'] = $this->request->param('channel_id');
                    $group['model'] = $this->request->param('model');

                    $sn = explode("\n", trim($this->request->param('sn')));
                    foreach ($sn as $item) {
                        if (trim($item) != '' && !PosModel::where('sn', $item)->find()) {

                            $group['sn'] = $item;
                            $insertAll[] = $group;
                        }
                    }

                    $excel_id = $this->request->param('excel_id', '');
                    $insertAll = [];
                    if ($excel_id) {
                        $info = AttachmentEvent::distinguish($excel_id);
                        if (is_array($info)) {
                            foreach ($info as $index => $item) {
                                if ($index > 0) {
                                    if (!PosModel::where('sn', $item[2])->find()) {
                                        $group['sn'] = $item[2];
                                        $group['model'] = $item[6];
                                        unset($group['user_id']);
                                        unset($group['bind_time']);
                                        unset($group['activate_time']);
                                        if ($item[1]) {
                                            $user = UserModel::where('mobile', $item[1])->find();
                                            if ($user) {
                                                $group['user_id'] = $user['id'];
                                            }
                                        }
                                        if ($item[4]) {
                                            $group['bind_time'] = time_format(strtotime($item[4]));
                                        }
                                        if ($item[5]) {
                                            $group['activate_time'] = time_format(strtotime($item[5]));
                                        }
                                        $group['model'] = $item[7];
                                        $group['name'] = $item[6];
                                        $insertAll[] = $group;
                                    }
                                }
                            }
                        }
//                        dump(is_file($excel['path']));
                    }

                    $pos = new PosModel();
                    $c = $pos->saveAll($insertAll);
                    $data['message'] = '新增' . count($c) . '条成功';
                }

                $data['code'] = 0;
            } catch (Exception $e) {
                $data['code'] = 1;
                $data['message'] = $e->getMessage();
            }
            if (0 === $data['code']) {
                $this->_returnSuccess($data['message']);
            } else {
                $this->_returnError($data['message'], false);
            }
        } else {
            // 同步节点与菜单
            if ($this->request->param('id')) {
                $group_id = $this->request->param('id');
                $data = PosModel::where('id', $group_id)->find();
                if (!$data) {
                    $this->_returnError('POS机不存在');
                }
            } else {
                $data = [];
            }
            $param = [];

            $default_id = 0;


            $builder = new Edit();
            $builder->title('POS机管理')
                ->keyRadio('channel_id', '渠道', $param, '', $default_id)
                ->keyTextInline('name', '名称')
                ->keyTextInline('model', '型号');

            $builder->data($data)
                ->buttonSubmit();
            return $builder->fetch();
        }
    }


}
